package com.df.springmvc.common.services;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Blob;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import com.common.util.SN_GUID;
import com.df.springmvc.common.dao.FileDao;
import com.df.springmvc.supper.SupperServices;

/**
 * 本类只做数据运算处理
 * @author David
 */
@Service
public class FileServices extends SupperServices{
	@Autowired
	FileDao dao;
	/**
	 * 上传文件更改file upload插件
	 * @param request
	 * @param response
	 * @param m
	 * @return
	 */
	public Map upload1(HttpServletRequest request, HttpServletResponse response,HashMap<String, String> m){
		HttpSession session=request.getSession();
		String fileGroupId=m.get("fileGroupId");
		session.setAttribute("fileGroupId",fileGroupId);
		Map<String, Object> map = new HashMap<String,Object>();
        ArrayList<HashMap<String,Object>> fileNameIdList=new ArrayList<HashMap<String,Object>>();   
		// 创建一个通用的多部分解析器
		CommonsMultipartResolver multipartResolver=new CommonsMultipartResolver(request.getSession().getServletContext());
		// 判断 request 是否有文件上传,即多部分请求
		if(multipartResolver.isMultipart(request)){
			// 转换成多部分request
			MultipartHttpServletRequest multiRequest=(MultipartHttpServletRequest)request;
			// 取得request中的所有文件名
			Iterator<String> itr=multiRequest.getFileNames();
		        
	        while (itr.hasNext()) {
	        	// 取得上传文件
				List<MultipartFile> files=multiRequest.getFiles(itr.next());
				for(MultipartFile file:files){
					if(file != null){
						// 取得当前上传文件的文件名称
						String myFileName=file.getOriginalFilename();
						// 如果名称不为“”,说明该文件存在，否则说明该文件不存在
						if(myFileName.trim() != ""){
							// 重命名上传后的文件名
							try{
								String fileName=SN_GUID.getUUID() + myFileName.substring(myFileName.lastIndexOf("."));
								HashMap<String,Object> tmp_=new HashMap<String,Object>();
								tmp_.put("id",fileName);
								tmp_.put("type",myFileName.substring(myFileName.lastIndexOf(".")));
								tmp_.put("path","");
								tmp_.put("name",myFileName);
								if(file.getSize() * 1.0 / 1024 / 1024 >= 1){
									tmp_.put("size",new DecimalFormat("0.00").format(file.getSize() * 1.0 / 1024 / 1024) + "MB");
								}else if(file.getSize() * 1.0 / 1024 >= 1){
									tmp_.put("size",new DecimalFormat("0.00").format(file.getSize() * 1.0 / 1024) + "KB");
								}else{
									tmp_.put("size",new DecimalFormat("0.00").format(file.getSize() * 1.0 / 1024) + "KB");
								}
								// 定义上传路径
								String baseFileName =new String(Base64.encodeBase64(myFileName.getBytes("utf-8")),"utf-8");
								
								String path=webPath + "upload/" + fileName + "/" + baseFileName.replace("/","=");
								if(new File(path).getParentFile().exists() == false){
									new File(path).getParentFile().mkdirs();
								}
								File localFile=new File(path);
								file.transferTo(localFile);
								tmp_.put("resultInfo", "已完成");
								fileNameIdList.add(tmp_);
							}catch(IllegalStateException e){
								// TODO Auto-generated catch block
								e.printStackTrace();
							}catch(IOException e){
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
						}
					}
				}
	        }
        } 
		map.put("files", fileNameIdList);
		return map;
	}
	public String upload(HttpServletRequest request,HashMap<String,String> map){
		HttpSession session=request.getSession();
		String fileGroupId=map.get("fileGroupId");
		session.setAttribute("fileGroupId",fileGroupId);
		ArrayList<HashMap<String,Object>> fileNameIdList=new ArrayList<HashMap<String,Object>>();
		// 创建一个通用的多部分解析器
		CommonsMultipartResolver multipartResolver=new CommonsMultipartResolver(request.getSession().getServletContext());
		// 判断 request 是否有文件上传,即多部分请求
		if(multipartResolver.isMultipart(request)){
			// 转换成多部分request
			MultipartHttpServletRequest multiRequest=(MultipartHttpServletRequest)request;
			// 取得request中的所有文件名
			Iterator<String> iter=multiRequest.getFileNames();
			while(iter.hasNext()){
				// 记录上传过程起始时的时间，用来计算上传时间
				int pre=(int)System.currentTimeMillis();
				// 取得上传文件
				List<MultipartFile> files=multiRequest.getFiles(iter.next());
				for(MultipartFile file:files){
					if(file != null){
						// 取得当前上传文件的文件名称
						String myFileName=file.getOriginalFilename();
						// 如果名称不为“”,说明该文件存在，否则说明该文件不存在
						if(myFileName.trim() != ""){
							// 重命名上传后的文件名
							try{
								String fileName=SN_GUID.getUUID() + myFileName.substring(myFileName.lastIndexOf("."));
								HashMap<String,Object> tmp_=new HashMap<String,Object>();
								tmp_.put("id",fileName);
								tmp_.put("type",myFileName.substring(myFileName.lastIndexOf(".")));
								tmp_.put("path","");
								tmp_.put("name",myFileName);
								if(file.getSize() * 1.0 / 1024 / 1024 >= 1){
									tmp_.put("size",new DecimalFormat("0.00").format(file.getSize() * 1.0 / 1024 / 1024) + "MB");
								}else if(file.getSize() * 1.0 / 1024 >= 1){
									tmp_.put("size",new DecimalFormat("0.00").format(file.getSize() * 1.0 / 1024) + "KB");
								}else{
									tmp_.put("size",new DecimalFormat("0.00").format(file.getSize() * 1.0 / 1024) + "KB");
								}
								fileNameIdList.add(tmp_);
								// 定义上传路径
								System.out.println("wwww"+myFileName);
								String path=webPath + "upload/" + fileName + "/" + new String(Base64.encodeBase64(myFileName.getBytes("utf-8")),"utf-8");
								if(new File(path).getParentFile().exists() == false){
									new File(path).getParentFile().mkdirs();
								}
								System.out.println(path+"===");
								File localFile=new File(path);
								file.transferTo(localFile);
							}catch(IllegalStateException e){
								// TODO Auto-generated catch block
								e.printStackTrace();
							}catch(IOException e){
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
						}
					}
					// 记录上传该文件后的时间
					int finaltime=(int)System.currentTimeMillis();
					System.out.println((finaltime - pre) + "ms");
				}
			}
		}
		session.setAttribute(fileGroupId,fileNameIdList);
		return "";
	}
	public void doConfirm(HttpServletRequest request,HashMap<String,String> paramMap) throws Exception{
		// TODO Auto-generated method stub
		HttpSession session=request.getSession();
		if(paramMap.isEmpty()){
			throw new Exception("上传文件为空,请检查文件列表中是否有文件");
		}
		String[] upload_fileIds=("" + paramMap.get("upload_fileId")).split(",");
		String[] upload_fileNames=("" + paramMap.get("upload_fileName")).split(",");
		if(upload_fileIds == null){
			return;
		}
		for(int i=0;i < upload_fileIds.length;i++){
			String upload_fileId=upload_fileIds[i];
			String path=webPath + "upload/" + upload_fileId;
			File fileName=new File(path);// 上传文件夹
			String upload_fileName=upload_fileNames[i];
			String base64fileName="";
			for(String f:fileName.list()){// 查询文件夹下的文件
				base64fileName=f;
			}
			HashMap<String,Object> map=new HashMap<String,Object>();
			// fileList.add(upload_fileId);
			File file=new File(path + "/" + base64fileName);
			map.put("guid",SN_GUID.getUUID());
			map.put("status","1");
			map.put("createby",getCurrentUserBean().getUserId());
			map.put("createtime",new Date());
			map.put("updateby",getCurrentUserBean().getUserId());
			map.put("updatetime",new Date());
			map.put("status","1");
			map.put("fileId",upload_fileId);
			map.put("fileName",upload_fileName);
			map.put("fileRoute",upload_fileId + "/" + base64fileName);
			map.put("fileSize",file.length());
			map.put("fileAuthor","system");
			map.put("fileType",upload_fileId.substring(upload_fileId.lastIndexOf(".")));
			map.put("fileGroupId",session.getAttribute("fileGroupId"));
			InputStream is=null;
			try{
				is=new FileInputStream(file);
				byte[] b=new byte[is.available()];
				is.read(b);
				map.put("fileContent",b);
			}catch(Exception e){
				// TODO: handle exception
				e.printStackTrace();
			}finally{
				if(is != null){
					is.close();
				}
			}
			File localFile=new File(webPath + "cache/" + upload_fileId + "/" + base64fileName);
			if(localFile.getParentFile().exists() == false){
				localFile.getParentFile().mkdirs();
			}
			org.apache.log4j.Logger.getLogger(getClass()).info("开始提交文件:" + file);
			file.renameTo(localFile);
			dao.add(map);
		}
	}
	public Object image(HttpServletRequest request,HttpServletResponse response,HashMap<String,String> paramMap) throws Exception{
		// TODO Auto-generated method stub
		System.out.println(paramMap);
		HashMap<String,Object> map=new HashMap<String,Object>();
		String fileId=paramMap.get("fileId");
		File localFile=new File(webPath + "cache/" + fileId);
		if(localFile.exists() == false){
			org.apache.log4j.Logger.getLogger(getClass()).info("本地文件不存在,查询数据文件.");
			HashMap<String,Object> tmap=dao.query(fileId);
			String fileName="" + tmap.get("fileName");
			Object fileContent=tmap.get("fileContent");
			String fileNameBase64=new String (Base64.decodeBase64(fileName.getBytes("utf-8")),"utf-8");
			fileNameBase64=fileNameBase64.replace("/","#1#");
			fileNameBase64=fileNameBase64.replace("\\","#2#");
			fileNameBase64=fileNameBase64.replace(" ","#3#");
			File ff=new File(localFile + "/" + fileNameBase64);// 文件
			byte[] content=null;
			//////mysql user byte[]
			if(fileContent instanceof byte[]){
				 content=(byte[])fileContent;
			}else{
				Blob seb=(java.sql.Blob)fileContent;
					int s=seb.getBinaryStream().available();
					 content=new byte[s];
					seb.getBinaryStream().read(content);
			}
			
		
			
		
			if(ff.getParentFile().exists() == false){
				ff.getParentFile().mkdirs();
			}
			FileOutputStream fos=new FileOutputStream(ff);
			try{
				fos.write(content);
			}catch(Exception e){
				// TODO: handle exception
				e.printStackTrace();
			}finally{
				fos.close();
			}
		}else{
			org.apache.log4j.Logger.getLogger(getClass()).info("本地文件存在");
		}
		String fileName="";
		byte[] content=null;
		for(String f:localFile.list()){
			
			String fileNameBase64=f;
			System.out.println("===="+fileNameBase64);
			fileNameBase64=fileNameBase64.replace("#1#","/");
			fileNameBase64=fileNameBase64.replace("#2#","\\");
			fileNameBase64=fileNameBase64.replace("#3#"," ");
			fileName=new String(Base64.decodeBase64(fileNameBase64),"utf-8");
			File ff=new File(localFile + "/" + f);// 文件
			FileInputStream fis=null;
			try{
				fis=new FileInputStream(ff);// 文件流
				content=new byte[fis.available()];
				fis.read(content);
			}catch(Exception e){
				// TODO: handle exception
				e.printStackTrace();
			}finally{
				if(fis != null){
					fis.close();
				}
			}
		}

		map.put("filename",fileName);
		map.put("content",content);
		return map;
	}
	@Override
	public Object del(HashMap<String,String> paramMap) throws Exception{
		// TODO Auto-generated method stub
		dao.del(new HashMap<String,Object>(paramMap));
		return super.del(paramMap);
	}
	public ArrayList<HashMap<String,Object>> getFileList(HashMap<String,String> paramMap) throws Exception{
		// TODO Auto-generated method stub
		return dao.getFileList(paramMap.get("fileGroupId"));
	}
}
